package net.wanho.zaixian.course.service.impl;

import net.wanho.zaixian.course.dao.CmsPageDao;
import net.wanho.zaixian.course.service.CmsPageService;
import net.wanho.zaixian.pojo.cms.CmsPage;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class CmsPageServiceImpl implements CmsPageService {

    @Resource
    private CmsPageDao cmsPageDao;

    /**
     * 查询所有的页面
     * @param page
     * @param size
     * @param siteId
     * @return
     */
    @Override
    public Page listPage(int page, int size,
                         @RequestParam(required = false ,name = "siteId") String siteId) {

        ExampleMatcher exampleMatcher =
                ExampleMatcher.matching().//创建自动匹配查询器
                        withMatcher("siteId", ExampleMatcher.GenericPropertyMatchers.contains()).//全局模糊查询
                        withIgnorePaths("_class");

        /**
         *  PageRequest.of(1, 2);
         *  该静态方法返回一个------>返回of方法的对象，参数sort.unsort (不加密)------>继续调用返回一个new PageRequest接口对象
         */
        CmsPage cmsPage = new CmsPage();
        if(siteId !=null && !"".trim().equals(siteId.trim())){
            cmsPage.setSiteId(siteId);
        }
        Example<CmsPage> example = Example.of(cmsPage, exampleMatcher);
        Pageable pageable = PageRequest.of(page-1, size);
        Page list = cmsPageDao.findAll(example,pageable);
        return list;
    }


    /**
     *
     * 增加一个页面
     * @param cmsPage
     * @return
     */
    @Override
    public void addPage(CmsPage cmsPage) {
        cmsPageDao.insert(cmsPage);
    }

    /**
     * 根据id查询页面
     */
    @Override
    public Optional<CmsPage> getPage(String pageId) {
        Optional<CmsPage> optionalCmsPage = cmsPageDao.findById(pageId);


        return optionalCmsPage;
    }


    /**
     * 根据id修改页面
     * @param pageId
     * @param cmsPage
     * @return
     */
    @Override
    public void editPage(String pageId, CmsPage cmsPage) {
        cmsPage.setPageId(pageId);
        cmsPageDao.save(cmsPage);

    }


    /**
     * 删除page
     * @param pageId
     * @return
     */
    @Override
    public void delPage(String pageId) {
        cmsPageDao.deleteById(pageId);
    }
}
